{extend name="common/main"/}
{block name="style"}
<script src="__STATIC__/common/lib/vue/vue-2.6.14.js"></script>
{/block}
{block name="body"}
<div class="update-warp " v-cloak>
    <div class="main-title">
        {if $scene == 'setup'}
        <h2>在线安装</h2>
        {else /}
        <h2>在线更新</h2>
        {/if}
    </div>
    <div class="with-padding main">
        <div class="upgrade-icon">
            <img alt="" src="__STATIC__/common/images/update.gif">
        </div>
        <!-- 进度条 -->
        <div :class="{'active':status == 0}" class="progress progress-striped" v-if="status!=-1">
            <div :style="{width:`${progressVal}%`}" aria-valuemax="100" class="progress-bar" role="progressbar"></div>
        </div>
        <!--进度描述-->
        <div class="progress-info">
            <div class="progress-title">{{progressTitle}}</div>
            <div :class="{'task-error':status == -1}" class="task">{{task}}</div>
            <div class="progress-num" v-if="status!=-1">{{progressVal}}%</div>
        </div>

        <div class="error-panel panel" v-if="errPackage.length > 0">
            <div class="panel-heading">
                <h4>错误信息</h4>
            </div>
            <div class="panel-body">
                <table class="table table-borderless">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>错误信息</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="(item,index) in errPackage">
                        <td :title="item.data.name" class="error-file" data-placement="top" data-toggle="tooltip">
                            {{item.data.name}}
                        </td>
                        <td class="error-msg">{{item.msg}}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="btn-menu">
            <button @click="back()" class="btn btn-lg btn-default" v-if="status == -1">返回</button>
            <button @click="jump()" class="btn btn-lg btn-primary" v-if="status == 1">确定</button>
        </div>
    </div>
</div>
{/block}
{block name="script"}
<script>
    var vm = new Vue({
        el: '.update-warp',
        data: {
            scene: '{$scene}', // 使用场景 setup 安装 upgrade 更新
            authCode:'{$authCode}',
            progressVal: 0,//进度值
            status: 0,//更新状态 -1异常 0 进行中 1 已完成
            progressTitle: '获取信息中',//进度标题
            task: '',//进行任务
            appName: '{$appName}',//应用类型 0系统 1应用
            api: '{$cloud}',//接口api
            localVersion: '{$version}',//本地版本
            upgradeVersion: '{$upgradeVersion}',//要升级的版本
            package: null,//更新包
            packageProgress: 0,//更新包进度
            packageTotal: 0,//更新包总大小
            errPackage: [],//发生更新错误包
            retrying: true,//重试
            versionPackage: {},//版本号升级文件
            skipUpgradeVersion: 0,//跳过更新版本号
        },
        created() {
            this.getUpgradeInfo();
        },
        methods: {
            /**
             * @title 获取应用升级信息
             */
            getUpgradeInfo() {
                let that = this;
                let api = '{:url("update/package")}';
                if(that.scene == 'setup'){
                    that.progressTitle = '正在获取安装包，请稍后...';
                }else{
                    that.progressTitle = '正在获取升级包，请稍后...';
                }

                $.post(api, {
                    version: that.upgradeVersion,
                    auth_code:that.authCode,
                    app_name:that.appName,
                }, function (res) {
                    
                    if (res.code == 200) {
                        that.package = res.data.data;
                        that.packageTotal = res.data.total;
                        
                        if (that.upgradeVersion != that.localVersion){
                            if(that.scene == 'setup'){
                                that.progressTitle = '开始安装';
                            }else{
                                that.progressTitle = '开始升级';
                            }
                            
                            that.upgrade();
                        }else{
                            that.sameVersion();
                        }
                    } else {
                        that.status = -1;
                        that.progressTitle = '提示错误：';
                        that.task = res.msg
                    }
                })
            },
            async upgrade() {
                let that = this;
                let step = that.packageTotal / 100;//计算百分比 步进值
                if(that.package.length > 0){
                    let item = that.package[that.packageProgress];//当前升级包
                    that.progressVal = Math.floor(that.packageProgress / step);//进度条
                    that.task = '下载中 ' + item.name;//任务名称
                    that.progressTitle = '';
                    
                    if(that.appName == 'system' && item.name == 'data/version.ini'){
                        that.versionPackage.name = item.name
                        that.versionPackage.md5 = item.md5
                    }
                    $.post("{:url('upgrade')}", {
                        app_name: that.appName,
                        version: that.upgradeVersion,
                        file: item.name,
                        md5: item.md5
                    }, function (res) {
                        console.log(res)
                        if (res.data == 'same_version'){
                            that.sameVersion();
                        }else{
                            if (res.code != 200) {
                                //记录当前错误信息
                                let err = {
                                    msg: res.msg,
                                    data: item
                                };
                                that.errPackage.push(err);
                                // 发生错误跳过版本升级
                                that.skipUpgradeVersion = 1;
                            }

                            if (res.code != 401){
                                //继续执行
                                that.packageProgress++;
                                
                                if (that.packageProgress >= that.packageTotal) {
                                    //执行收尾工作
                                    that.finishUpgrade();
                                } else {
                                    //执行下一个
                                    that.upgrade();
                                }
                            }else{
                                that.task = '';
                                that.status = -1;
                                that.progressTitle = '未经授权,无法更新';
                                that.task = '';
                            }

                        }

                    })
                }else{
                    //执行收尾工作
                    that.finishUpgrade();
                }

            },
            /**
             * 无需升级
             */
            sameVersion(){
                let that = this;
                that.status = 1;
                that.progressTitle = '已经是最新版本了';
                that.task = '';
                that.progressVal = 100;
            },
            /**
             * 问题包重试
             */
            errRetry(i = 0) {
                let that = this;
                that.progressTitle = '重试中';
                let len = that.errPackage.length;
                if (i == len){
                    that.retrying = false;
                    that.finishUpgrade();
                    return false;
                }
                let item = that.errPackage[i]['data'];
                $.post("{:url('upgrade')}", {
                        app_name: that.appName,
                        version: that.upgradeVersion,
                        file: item.name,
                        md5: item.md5
                    }, function (res) {
                        if (res.code == 0){
                            that.skipUpgradeVersion = 1;
                        }
                        if (res.code == 200){

                        }
                        
                        that.errRetry(i + 1);
                    }
                )
            },
            /**
             * 执行收尾任务
             */
            finishUpgrade() {
                let that = this;
                // 问题包处理
                if (that.retrying) {
                    that.errRetry();
                    return false;
                }
                if(that.skipUpgradeVersion == 1){
                    that.progressTitle = '部分文件下载失败，请刷新重试！';
                    that.task = '';
                    that.progressVal = 100;
                    return false;
                }
                $.post("{:url('finish')}", {
                    app_name: that.appName,
                    version: that.upgradeVersion,
                    file: that.versionPackage.name,
                    md5: that.versionPackage.md5,
                    scene: that.scene,
                    skip: that.skipUpgradeVersion ? 1 : 0,
                }, function (res) {
                    if(res.code == 200){
                        //that.progressTitle = '安装完成';
                        that.status = 1;
                        if(that.scene == 'setup'){
                            that.progressTitle = '开始安装';
                            that.setupApp();
                        }else{
                            that.progressTitle = '升级完成';
                        }
                    }else{
                        that.progressTitle = '发生错误：' + res.msg;
                    }
                    
                    that.task = '';
                    that.progressVal = 100;
                })
            },
            /**
             * 安装应用
             */
            setupApp() {
                let that = this;
                that.progressTitle = '安装中...';
                $.post("{:url('admin/module/install')}", {
                    name: that.appName,
                }, function (res) {
                    if(res.code == 200){
                        that.progressTitle = '安装完成';
                    }else{
                        that.progressTitle = '发生错误：' + res.msg;
                    }
                })
            },
            back() {
                window.history.go(-1);
            },

            jump() {
                if(this.appName == 'system'){
                    window.history.go(-1);
                    window.location.href="{:url('admin/update/index')}";
                }else{
                    window.location.href="{:url('admin/module/index')}";
                }
            }
        }
    })
</script>
{/block}

